<script lang="ts" setup>
import type { ProcessItem } from '@vben/types';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref } from 'vue';

import { Button } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useAnalyticsStore } from '#/store';

const analyticsStore = useAnalyticsStore();

function bytesToMB(bytes: number | undefined, is_number: boolean = false) {
  if (bytes === undefined) return 0;
  // 将字节转换为GB，1GB = 1024 * 1024 * 1024 字节
  const gb = bytes / (1024 * 1024);
  if (is_number) return gb.toFixed(2);
  // 使用 toFixed 方法保留两位小数
  return `${gb.toFixed(2)} MB`;
}

const sorting = ref<string>('CPU');

const gridOptions: VxeGridProps<ProcessItem> = {
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { field: 'processID', title: '进程ID' },
    { field: 'name', title: '名称' },
    {
      field: 'processCpuLoadCumulative',
      title: 'CPU负载累积',
      formatter({ cellValue }) {
        return `${(Number(cellValue) * 100).toFixed(2)}%`;
      },
    },
    {
      field: 'residentSetSize',
      title: '物理内存',
      formatter({ cellValue }) {
        return bytesToMB(Number(cellValue));
      },
    },
    {
      field: 'virtualSize',
      title: '虚拟内存',
      formatter({ cellValue }) {
        return bytesToMB(Number(cellValue));
      },
    },
    { field: 'threadCount', title: '进程数量' },
    { field: 'commandLine', showOverflow: true, title: '命令行' },
    { field: 'path', showOverflow: true, title: '路径' },
    { field: 'currentWorkingDirectory', showOverflow: true, title: '工作目录' },
  ],
  proxyConfig: {
    sort: true,
    ajax: {
      query: async () => {
        const data = await analyticsStore.refreshProcess(10, sorting.value);
        return { records: data, total: 10 };
      },
    },
  },
  pagerConfig: {
    enabled: false,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

const handleSorting = (value: string) => {
  sorting.value = value;
  gridApi.query();
};
</script>

<template>
  <div class="mt-5">
    <Grid table-title="进程信息" class="px-3">
      <!-- <template #toolbar-buttons>
        <div class="w-full text-center text-lg">进程信息</div>
      </template> -->
      <template #toolbar-tools>
        <Button class="mr-2" @click="() => handleSorting('CPU')">CPU</Button>
        <Button class="mr-2" @click="() => handleSorting('MEM')">内存</Button>
      </template>
    </Grid>
  </div>
</template>
